import { useMutation } from "@apollo/react-hooks";
import { useEffect } from "react";
import gql from "graphql-tag";
import { notification } from "antd";

import { QUERY } from "./useTable";
import { usePageContext } from "./useContext";
import { handleErrors } from "../../../utils/handleErrors";
import { useForm } from "./useForm";
import { SYS_AUTHORITIES } from "../../SysRole/hooks/useAuthorities";

const CREATE = gql`
  mutation CreateSysAuthority($authority: CreateSysAuthorityInput!) {
    createSysAuthority(authority: $authority) {
      id
    }
  }
`;

export const useCreate = ({ form }) => {
  const { handleClose } = useForm();
  const {
    state: {
      form: { current, isEdit }
    },
    dispatch
  } = usePageContext();

  const [createSysAuthority] = useMutation(CREATE, {
    onCompleted: ({ createSysAuthority }) => {
      if (createSysAuthority) {
        notification.success({ message: "新建权限成功！" });
        handleClose();
      }
    },
    onError: ({ graphQLErrors, networkError }) => {
      handleErrors({ graphQLErrors, networkError, form });
    },
    refetchQueries: [
      {
        query: QUERY
      },
      { query: SYS_AUTHORITIES }
    ]
  });

  const handleSubmit = e => {
    e.preventDefault();
    form.validateFields((err, values) => {
      if (!err) {
        let { name, path, type, parentId, ...data } = values;
        const level = (current.level && current.level + 1) || 1;
        name = `${current.name || "AUTH"}_${name}`;
        path = type === "MENU" ? `${current.path || ""}/${path}` : null;
        createSysAuthority({
          variables: {
            authority: {
              ...data,
              name,
              path,
              type,
              parentId,
              level
            }
          }
        });
      }
    });
  };

  useEffect(() => {
    if (!isEdit) {
      if (current) {
        const currentLv = current.level;
        const children = current.children;
        if (currentLv && !children) {
          // first level with no children can create any
          dispatch({
            type: "SET_FORM",
            payload: { types: [false, false, false] }
          });
        }

        if (
          !currentLv ||
          (currentLv === 1 &&
            children &&
            children
              .map(({ type }) => type)
              .some(item => ["MENU"].includes(item)))
        ) {
          // main menu or first level with menu type sub items can only  create menu
          dispatch({
            type: "SET_FORM",
            payload: { types: [false, true, true] }
          });
        }

        if (
          currentLv === 2 ||
          (currentLv === 1 &&
            children &&
            children
              .map(({ type }) => type)
              .some(item => ["QUERY", "MUTATION"].includes(item)))
        ) {
          // second level or first level with non-menu sub items can only create non-menu item
          dispatch({
            type: "SET_FORM",
            payload: { types: [true, false, false] }
          });
        }
        dispatch({ type: "SET_FORM", payload: { handleSubmit } });
        dispatch({ type: "TOGGLE_MODAL", payload: true });
      } else {
        form.resetFields();
        dispatch({ type: "TOGGLE_MODAL", payload: false });
      }
    }
  }, [current, isEdit]);
};
